<?php
	namespace app\index\controller;

	use \think\Db;

	use \think\Log;

	class Base extends \think\Controller{

		protected $me;

		protected $redis;

		protected $key='zmyhlj!';

		protected $token='';

		protected $time=3600*24*30;//用户token存储时间

		protected $method='';

		public function __construct(){

			parent::__construct();

			$this->me=\think\Cache::store('memcache');

			$this->redis=new \Redis;


			$this->redis->connect('127.0.0.1',6379);

			$this->redis->auth('zmy2002.');

			$this->token=isset($_SERVER['HTTP_AUTHORIZATION'])?$_SERVER['HTTP_AUTHORIZATION']:'';

			$this->method=strtolower($_SERVER['REQUEST_METHOD']);

			// $this->redis->set($_SERVER['HTTP_ORIGIN'],1);

			// $this-
			
		}


		protected function getUser(){
			// 获取用户信息
			
			$user=[];

			if($this->token){
				$user=$this->redis->hgetall($this->token);
			}

			return $user;

		}

		private function close(){
			$config=$this->getCache('config',[],'c_key');
		}

		// 程序异常调用该方法
		protected function err($e){

			Log::write($e->getMessage(),'ERR');

			return json_encode(['msg'=>'服务器开了个小差','code'=>0]);

		}


		// 以die的形式输出json
		protected function json($arr=[]){

			die(json_encode($arr));
		}

		//返回数据
		protected function data($data=null){
			return json_encode(['msg'=>'','code'=>1,'data'=>$data]);
		}

		/*
		获取memacache缓存数据
		*$table 获取的表名
		*$where 条件
		*$id_key 如果不为空,查询的结果用id作为数组的键名
		 */
		
		/*,
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "https://packagist.phpcomposer.com"
        }
    }*/

		protected function getCache($table='',$where=[],$id_key=''){

			$row=$this->me->get($table);

			if(empty($row)){
				$data=Db::name($table)->where($where)->select();

				$row=[];

				if($id_key!=''){
					foreach($data as  $k=>$v){
						$row[$v[$id_key]]=$v;
					}
				}else{
					$row=$data;
				}

				$this->me->set($table,$row);

			}

			return $row;
		}

		// 递归查询分类下的所有子类
		protected function getCateAll($arr=[],$pid=0,$list=[]){
			foreach($arr as $k=>$v){
				if($v['c_parentId']==$pid){

					if($pid==0){

						$list[$v['c_id']][]=$v['c_id'];

					}else{
						foreach($list as $k2=>$v2){

							if(in_array($v['c_parentId'],$v2)){

								$list[$k2][]=$v['c_id'];

								// var_dump($list[$k2]);
							}
						}
					}



					$list=$this->getCateAll($arr,$v['c_id'],$list);
				}
			}

			return $list;
		}

	}
?>